﻿using System;
using System.ComponentModel;

namespace LogoFX.Infra
{
    public static class ConverterHelper
    {
        public static object ConvertToType(object value, Type type)
        {
            if (value != null)
            {
                if (type.IsAssignableFrom(value.GetType()))
                {
                    return value;
                }
                var typeConverter = GetTypeConverter(type);
                if ((typeConverter != null) && typeConverter.CanConvertFrom(value.GetType()))
                {
                    value = typeConverter.ConvertFrom(value);
                    return value;
                }
            }
            return null;
        }

        public static TypeConverter GetTypeConverter(Type type)
        {
            var attribute = (TypeConverterAttribute)Attribute.GetCustomAttribute(type, typeof(TypeConverterAttribute), false);
            if (attribute != null)
            {
                try
                {
                    Type converterType = Type.GetType(attribute.ConverterTypeName, false);
                    if (converterType != null)
                    {
                        return (Activator.CreateInstance(converterType) as TypeConverter);
                    }
                }
                catch
                {
                    // note we absorb this
                }
            }

            return TypeDescriptor.GetConverter(type);
        }
    }

}
